package com.fdbs.util;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FdfsUtils {
    static {
        try {
            String absolutePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(absolutePath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception
     */

    public static String[] up_load(FileUtils file) throws Exception {
        NameValuePair[] nameValuePairs = new NameValuePair[1];
        nameValuePairs[0] = new NameValuePair("author", "zwj");
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer connection = trackerClient.getConnection();
        StorageClient storageClient = new StorageClient(connection, null);
        String[] strings = storageClient.upload_file(file.getContent(), file.getExt(), nameValuePairs);
        return strings;

    }

    /**
     * 文件下载
     */
    public static InputStream downFile (String groupName , String remote_filename ) throws IOException, MyException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer connection = trackerClient.getConnection();
        StorageClient storageClient=new StorageClient(connection,null);
        byte[] bytes = storageClient.download_file(groupName, remote_filename);
        return new ByteArrayInputStream(bytes);

    }

    public static void main(String[] args) throws IOException, MyException {
        InputStream inputStream = FdfsUtils.downFile("group1", "M00/00/00/rBBJml7iKyqAG2MuAADjMIL9FwQ415.jpg");
        FileOutputStream fileOutputStream=new FileOutputStream("D:\\1.jpg");
        byte[] bytes=new byte[1024];
        while (inputStream.read(bytes)!=-1){
            fileOutputStream.write(bytes);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
        inputStream.close();
    }
}
